<?php
/*
Template Name: Orders Overview
*/
?>

<?php
$aOptions = SofaSuppaStore::initOptions( false );
$entrycurrency = $aOptions[ 'entrycurrency' ];
$currency_code = $aOptions[ 'paypalcurrency' ];
$checkout_tax  = floatval( $aOptions[ 'checkout_tax' ] );
$checkout_ship = stripslashes( strip_tags( $aOptions[ 'checkout_ship' ] ) );
$checkout_ship = floatval( $checkout_ship );
if( $checkout_tax < 0 ) $checkout_tax = 0;

// colorbox
$cb_width = ( strlen( $aOptions[ 'cb_width' ] ) > 0 ) ? intval( $aOptions[ 'cb_width' ] ) : 660;
$cb_height = ( strlen( $aOptions[ 'cb_height' ] ) > 0 ) ? intval( $aOptions[ 'cb_height' ] ) : 450;
$cb_height_small = ( strlen( $aOptions[ 'cb_height_small' ] ) > 0 ) ? intval( $aOptions[ 'cb_height_small' ] ) : 300;
?>

<?php get_header(); ?>

<!-- main content start -->

	<?php if( have_posts() ) : while( have_posts() ) : the_post(); ?>
    
    <div class="grid_12 clearfix">
    
    <!-- title start -->

    <h1><?php the_title(); ?></h1>
    
    <!-- title end -->
    
    <!-- pre-content (if any) start -->
    
    <?php the_content(); ?>
    
    <!-- pre-content (if any) end -->
    
    <!-- search label start -->
    
    <div class="grid_2 alpha">
        <span class="sfspan nomarg"><?php _e( "SEARCH TABLE", "sofa_suppastore" ); ?></span>
    </div>
    
    <!-- search label end -->
    
    <!-- search input start -->
    
    <div class="grid_5">
        <input type="text" class="grid_5 alpha" size="35" id="txtSearch" name="txtSearch" tabindex="998" />
    </div>
    
    <!-- search input end -->
    
    <!-- reset, expand buttons start -->
    
    <div class="grid_2">

		<span id="imgSearch" class="addtocart srchfilterbig">
        	<a rel="nofollow" href="#"><?php _e( "Reset", "sofa_suppastore" ); ?></a>
        </span>
        <span style="display: block; float: left; width: 1px; height: 1px; line-height: 0;">&nbsp;</span>
        
    </div>
    
    <div class="grid_3 omega">

		<span class="addtocart srchfilterbig">
        	<a rel="nofollow" id="expander" href="#"><?php _e( "Expand all table rows", "sofa_suppastore" ); ?></a>
        </span>
        
    </div>
    
    <!-- reset, expand buttons end -->
    
    <!-- content start -->
    
    <div class="grid_12 clearfix alpha omega">&nbsp;</div>
    
    <?php
	// only Admin is allowed to see orders table
	global $current_user;
	get_currentuserinfo();
    if( current_user_can( 'administrator' ) ) {
		
		global $wpdb;
		$global_counter = 1;
		$transactions = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "purchases_history ORDER BY trans_date DESC" );
		// make a custom loop through all orders
		if( $transactions ) {
			
	?>
    
    <!-- all orders overview start -->
    
    <table id="tblmeta" width="100%" border="0" cellspacing="0" cellpadding="0">
    
        <tr id="tblheaders">
            <th scope="col" class="textleft"><?php _e( "Order ID", "sofa_suppastore" ); ?></th>
            <th scope="col" class="center"><?php _e( "Order Date", "sofa_suppastore" ); ?></th>
            <th scope="col" class="center"><?php _e( "Transaction ID", "sofa_suppastore" ); ?></th>
            <th scope="col" class="center"><?php _e( "Buyer Name (status)", "sofa_suppastore" ); ?></th>
            <th scope="col" class="center"><?php _e( "Gross", "sofa_suppastore" ); ?></th>
            <th scope="col" class="textleft"><?php _e( "Order Status", "sofa_suppastore" ); ?></th>
            <th scope="col" class="textright" width="60"><?php _e( "Delete?", "sofa_suppastore" ); ?></th>
        </tr>
        
        <?php
		
		foreach( $transactions as $transaction ) {
			
			$purchase_id = $transaction->id; // ID
			$purchase_date = $transaction->trans_date; // date
			$purchase_code = $transaction->unique_code; // unique code returned by Paypal
			$purchase_basket = $transaction->trans_basket; // in da basket
			$purchase_buyer = $transaction->user_name; // user name, last name
			$purchase_buyer_status = $transaction->trans_status; // user verified?
			$purchase_buyer_email = $transaction->user_email; // user email
			$purchase_buyer_phone = $transaction->user_phone; // user phone
			$purchase_buyer_address = $transaction->user_address;
			$purchase_buyer_zipcode = $transaction->user_zip;
			$purchase_buyer_city = $transaction->user_city;
			$purchase_buyer_country = $transaction->user_country;
			$purchase_buyer_currency = $transaction->currency;
			$purchase_buyer_gross = $transaction->gross;
			$purchase_buyer_discount = $transaction->discount;
			$purchase_buyer_handling = $transaction->handling;
			$purchase_buyer_tax = $transaction->tax;
			$purchase_buyer_flag_shipped = $transaction->flag_shipped;
			
			$class_switch = ' light';
			if( $global_counter % 2 == 0 ) $class_switch = ' dark';
			
			// change status link
			$edit_order_status_link = get_template_directory_uri() . '/order_flag_n664x999_ss.php?itemid=' . $purchase_id;
			// delete order link
			$delete_order_link = get_template_directory_uri() . '/order_delete_z775y888_ss.php?itemid=' . $purchase_id;
		?>
        
            <tr>
            
            <td class="textleft<?php echo $class_switch; ?>"><?php echo $purchase_id; ?></td>
            <td class="center<?php echo $class_switch; ?>"><?php echo date( get_option( 'date_format' ), strtotime( $purchase_date ) ); ?></td>
            <td class="center<?php echo $class_switch; ?>"><?php echo '<a id="order_' . $global_counter . '" class="toggler" href="#" title="' . __( "Order Details", "sofa_suppastore" ) . '">' . $purchase_code . '</a>'; ?></td>
            <td class="center<?php echo $class_switch; ?>"><?php echo $purchase_buyer . ' (' . $purchase_buyer_status . ')'; ?></td>
            
            <td class="center<?php echo $class_switch; ?>"><?php echo $purchase_buyer_currency . ' ' . $purchase_buyer_gross; ?></td>
            
            <?php if( $purchase_buyer_flag_shipped == 0 ) { ?>
            <td class="textleft statuser optionpending<?php echo $class_switch; ?>">
			<?php echo '<a href="' . $edit_order_status_link . '" class="cboxElement pending">' . __( "Pending", "sofa_suppastore" ) . '</a>'; ?>
            </td>
            <?php } elseif( $purchase_buyer_flag_shipped == 1 ) { ?>
            <td class="textleft statuser optionshipped<?php echo $class_switch; ?>">
			<?php echo '<a href="' . $edit_order_status_link . '" class="cboxElement shipped">' . __( "Shipped", "sofa_suppastore" ) . '</a>'; ?>
            </td>
            <?php } elseif( $purchase_buyer_flag_shipped == 2 ) { ?>
            <td class="textleft statuser optionreturned<?php echo $class_switch; ?>">
			<?php echo '<a href="' . $edit_order_status_link . '" class="cboxElement returned">' . __( "Returned", "sofa_suppastore" ) . '</a>'; ?>
            </td>
            <?php } ?>
            
            <td class="textright deleter<?php echo $class_switch; ?>">
			<?php 
			echo '<a href="' . $delete_order_link . '" class="coedit textright delitem cboxElement">';
			echo '<img src="' . get_template_directory_uri() . '/images/delete_cart18x18.gif" alt="' . __( "Delete Item", "sofa_suppastore" ) . '" />';
			echo '</a>'; 
			?>
            </td>
            
            </tr>
            
            <tr id="metabasket_<?php echo $global_counter; ?>" style="display: none;">
            
            <td class="textleft<?php echo $class_switch; ?>" colspan="4">
            
			<?php 
			echo '<h4>' . __( "Shipped to:", "sofa_suppastore" ) . '</h4>';
			echo $purchase_buyer . '<br />';
			echo $purchase_buyer_address . '<br />';
			echo $purchase_buyer_city . ', ' . $purchase_buyer_zipcode . '<br />';
			$arr_pbc = explode( '~', $purchase_buyer_country );
			echo $arr_pbc[ 0 ] . '<br />';
			echo __( "Phone", "sofa_suppastore" ) . ': ' . $purchase_buyer_phone . '<br />';
			echo __( "E-mail address", "sofa_suppastore" ) . ': <br /><a href="mailto:' . $purchase_buyer_email . '">' . $purchase_buyer_email . '</a>';
			?>
            
            </td>
            
            <td class="textleft<?php echo $class_switch; ?>" colspan="3">
			
			<?php 
			echo '<h4>' . __( "Basket", "sofa_suppastore" ) . '</h4>';
			// what was in da basket?
			$arr_items_in_basket = explode( '^', $purchase_basket );
			array_pop( $arr_items_in_basket ); // remove last empty element
			$aiib_len = count( $arr_items_in_basket );
			
			if( $aiib_len > 0 ) {
				
				$cnt_aiib        = 0;
				$items_sum       = 0;
				$shipping_sum    = 0;
				$total_sum       = 0;
				$output_userdata = '';
				
				while( $cnt_aiib < $aiib_len ) {
					
					$single_item_arr = explode( '~', $arr_items_in_basket[ $cnt_aiib ] ); // ID~Product Name~Size~Quantity~Price~Individual Shipping Price
					$single_item_id    = intval( $single_item_arr[ 0 ] ); // product id
					$single_item_name  = $single_item_arr[ 1 ]; // product name
					$single_item_size  = $single_item_arr[ 2 ]; // product size
					$single_item_qty   = intval( $single_item_arr[ 3 ] ); // quantity
					$single_item_price = number_format( $single_item_arr[ 4 ], 2, '.', '' ); // single price
					$single_item_shipp = ( $single_item_arr[ 5 ] ) ? number_format( $single_item_arr[ 5 ], 2, '.', '' ) : 0; // shipping price
					
					$output_userdata .= ( '#' . $single_item_id . ', ' );
					$output_userdata .= ( $single_item_name . '<br />' );
					$output_userdata .= ( __( "Size", "sofa_suppastore" ) . ': ' . $single_item_size . ' | ' );
					$output_userdata .= ( __( "Quantity", "sofa_suppastore" ) . ': ' . $single_item_qty . '<br />' );
					$output_userdata .= ( __( "Item Price", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $single_item_price, 2, '.', '' ) . '<br />' );
					$calc_item_total = $single_item_qty * $single_item_price;
					$output_userdata .= ( __( "Item(s) Total", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $calc_item_total, 2, '.', '' ) . '<br />' );
					
					if( $single_item_shipp > 0 ) {
						$output_userdata .= ( __( "Shipping Price x Qty", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $single_item_shipp, 2, '.', '' ) . '<br />' );
						$shipping_sum = $shipping_sum + $single_item_shipp;
					}
					
					$output_userdata .= '----------------------------------------<br />';
					
					$items_sum = $items_sum + $calc_item_total;
					
					$cnt_aiib ++;
					
				}
				
				$shipping_sum = $shipping_sum + $purchase_buyer_handling;
				
				// discount aka coupon code or voucher
				if( $purchase_buyer_discount > 0 ) {
					$output_userdata .=  __( "Discount", "sofa_suppastore" ) . ' - ' . $purchase_buyer_currency . ' ' . number_format( $purchase_buyer_discount, 2, '.', ',' ) . '<br />';
					$items_sum = $items_sum - $purchase_buyer_discount;
				}
				
				$output_userdata .=  __( "Subtotal", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $items_sum, 2, '.', ',' ) . '<br />';
				
				if( $purchase_buyer_tax > 0 ) {
					$output_userdata .=  __( "Tax", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $purchase_buyer_tax, 2, '.', ',' ) . '<br />';
				}
				
				$output_userdata .= __( "Shipping and Handling", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $shipping_sum, 2, '.', ',' ) . '<br />';
				
				$output_userdata .= '----------------------------------------<br />';
				
				$output_userdata .= '<span class="alltotal">' . __( "Total", "sofa_suppastore" ) . ': ' . $purchase_buyer_currency . ' ' . number_format( $purchase_buyer_gross, 2, '.', ',' ) . '</span>';
				
				echo $output_userdata;
				
			}
			?>
            
            </td>

            </tr>
        
        <?php
			
			$global_counter ++;
			
		}
		
		?>
      
    </table>
    
    <!-- all orders overview end -->
    
    <?php
			
		}
	}
	
	?>
    
    </div>

	<?php endwhile; ?>
    
    <!-- content end -->
    
	<script type='text/javascript'>
	
        // on-page table search functions
		
		var all_up = 0;
		jQuery.expr[ ":" ].containsNoCase = function( el, i, m ) {
            var search = m[ 3 ];
            if( !search ) return false;
			return new RegExp( search, "i" ).test( jQuery( el ).text() );
        };
    
        jQuery( document ).ready( function() {
            
            // colorbox
            jQuery( '.statuser a' ).colorbox( { width: "<?php echo $cb_width . 'px'; ?>", height: "<?php echo ( $cb_height_small + 20 ) . 'px'; ?>", iframe: true } );
			jQuery( '.deleter a' ).colorbox( { width: "<?php echo $cb_width . 'px'; ?>", height: "<?php echo ( $cb_height_small + 20 ) . 'px'; ?>", iframe: true } );
			
			// show-hide order details
			jQuery( "a.toggler" ).click( function( event ) {
				var objclicked = jQuery( this ).attr( 'id' );
				var prefix_array = objclicked.split( "_" );
				var trgt_num = parseInt( prefix_array[ 1 ] );
				
				if( trgt_num > 0 ) {
					trgt = "#metabasket_" + trgt_num;
					jQuery( trgt ).toggle( 'fast' );
				}
				
				return false;
			} );
			
			// table search
			jQuery( "#expander" ).click( function( event ) {
				if( !all_up ) {
					jQuery( '#tblmeta tr' ).show();
					all_up = 1;
				} else {
					jQuery( '#tblmeta tr[id^=metabasket_]' ).hide();
					all_up = 0;
				}
				return false;
			} );
			
            jQuery( '#imgSearch' ).hide();

            jQuery( '#imgSearch' ).click( function() {
                resetSearch();
				return false;
            });

            jQuery( '#txtSearch' ).keyup( function( event ) {
                if ( event.keyCode == 27 ) {
                    resetSearch();
                }
            } );

            // execute the search
            jQuery( '#txtSearch' ).keyup( function() {
                // only search when there are 3 or more characters in the textbox
                if( jQuery( '#txtSearch' ).val().length > 2 ) {
                    jQuery( '#tblmeta tr:first' ).show();
                    jQuery( '#tblmeta tr td:containsNoCase(\'' + jQuery( '#txtSearch' ).val() + '\')' ).parent().show();
                    jQuery( '#imgSearch' ).show();
					jQuery( '.norecords' ).remove();
                } else {
					jQuery( '#tblmeta tr:gt(0)' ).hide();
                    jQuery( '.norecords' ).remove();
                    jQuery( '#tblmeta' ).append( "<tr class='norecords'><td colspan='7'><?php _e( "Nothing found!", "sofa_suppastore" ); ?><\/td><\/tr>" );
				}
                if( jQuery( '#txtSearch' ).val().length == 0 ) {
                    resetSearch();
                }
				if( jQuery( '#tblmeta tr[id^=metabasket_]' ).css( 'display' ) == 'table-row' ) {
					jQuery( '.norecords' ).remove();
				}
            } );
			
		} );
		
        function resetSearch() {
            jQuery( '#txtSearch' ).val( '' );
            jQuery( '#tblmeta tr' ).show();
			jQuery( '#tblmeta tr[id^=metabasket_]' ).hide();
            jQuery( '.norecords' ).remove();
            jQuery( '#imgSearch' ).hide();
            jQuery( '#txtSearch' ).focus();
        }
		
	</script>
    
    <?php else : ?>
    
    <!-- no content start -->

	<div class="castshadow grid_12 clearfix">
    
        <h1><?php _e( "Nothing found!", "sofa_suppastore" ); ?></h1>
        <p><?php _e( "Sorry but no posts found. Take your time, there's gonna be soon to see something listed here.", "sofa_suppastore" ); ?></p>
    
    </div>
    
    <!-- no content end -->

	<?php endif; ?>
    
<!-- main content end -->

<?php get_footer(); ?>